package com.smileus.integration.caller;

import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.smileus.common.CallInfo;
import com.smileus.common.Env;
import com.smileus.integration.cluster.divert.Diverter;
import com.smileus.service.ClusterService;

public abstract class AbstractCaller implements Caller {
	protected static final Log logger = LogFactory.getLog(AbstractCaller.class);
	protected static ClusterService clusterService = Env.getBean("defaultClusterService", ClusterService.class);
	private static Diverter diverter = Env.getBean("diverter", Diverter.class);

	public CallInfo getCallInfo(String serviceId) {
		return clusterService.getCallInfo(serviceId);
	}

	/**
	 * serviceId形式为katongprod.xxService.save,根据serviceId，定位到xxService发布在哪些机器上
	 * ，然后根据负载均衡算法，选出合适的服务主机URL
	 * 
	 * @param ServiceCaller
	 * @return String
	 */
	public String getURL(String serviceId) {
		// 通过负载均衡算法，确定服务资源的主机
		// TODO 注意，默认返回WS地址
		return diverter.getUrl(serviceId);
	}

	protected String toTargetHost(String url) {
		URL urlobj = null;
		try {
			urlobj = new URL(url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
			throw new RuntimeException("资源地址解析出错.");
		}
		return urlobj.getHost();
	}
}
